Page({
  data: {
    currentTab: 'minute',
    stockInfo: {},
    stockCode: '',
    stockName: '',
    chartUrl: '',
    buyOrders: [],
    sellOrders: [],
    newsList: [
      {
        title: '渤海汽车：渤海汽车2024年年度报告摘要',
        source: '交易所公告',
        time: '00:07'
      },
      {
        title: '渤海汽车：渤海汽车关于召开2024年度暨2025年第一季度业绩说明会的公告',
        source: '上交所股票',
        time: '00:02'
      },
      {
        title: '图解渤海汽车年报：第四季度单季净利润同比减1066.45%',
        source: '证券之星',
        time: '00:03'
      },
      {
        title: '渤海汽车：渤海汽车关于2024年度计提信用与资产减值准备的公告',
        source: '交易所公告',
        time: '00:01'
      }
    ]
  },

  onLoad: function(options) {
    const code = options.code;
    const name = options.name;
    
    this.setData({
      stockCode: code,
      stockName: name
    });
    
    wx.setNavigationBarTitle({
      title: `${name}(${code})`
    });
    
    this.getStockData(code);
    this.updateChartUrl(code);
    
    // 定时刷新数据
    this.dataTimer = setInterval(() => {
      this.getStockData(code);
    }, 10000); // 每10秒刷新一次
  },
  
  onUnload: function() {
    // 清除定时器
    if (this.dataTimer) {
      clearInterval(this.dataTimer);
    }
  },
  
  // 获取股票数据
  getStockData: function(code) {
    // 判断股票代码前缀
    const prefix = code.startsWith('6') ? 'sh' : 'sz';
    const fullCode = prefix + code;
    
    // 使用wx.request获取数据
    wx.request({
      url: `https://hq.sinajs.cn/list=${fullCode}`,
      header: {
        'content-type': 'application/json',
        'Referer': 'https://finance.sina.com.cn' // 新浪接口需要设置Referer
      },
      success: (res) => {
        if (res.data) {
          this.parseStockData(res.data);
        }
      },
      fail: (err) => {
        console.error('获取股票数据失败:', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 解析股票数据
  parseStockData: function(data) {
    try {
      // 从返回的字符串中提取数据部分
      const dataStr = data.split('="')[1].split('";')[0];
      const elements = dataStr.split(',');
      
      // 处理买卖盘数据
      const buyOrders = [
        { price: elements[11], volume: Math.floor(elements[10]/100) },
        { price: elements[13], volume: Math.floor(elements[12]/100) },
        { price: elements[15], volume: Math.floor(elements[14]/100) },
        { price: elements[17], volume: Math.floor(elements[16]/100) },
        { price: elements[19], volume: Math.floor(elements[18]/100) }
      ];
      
      const sellOrders = [
        { price: elements[21], volume: Math.floor(elements[20]/100) },
        { price: elements[23], volume: Math.floor(elements[22]/100) },
        { price: elements[25], volume: Math.floor(elements[24]/100) },
        { price: elements[27], volume: Math.floor(elements[26]/100) },
        { price: elements[29], volume: Math.floor(elements[28]/100) }
      ];
      
      // 计算涨跌幅
      const currentPrice = parseFloat(elements[3]);
      const yesterdayClose = parseFloat(elements[2]);
      const priceChange = (currentPrice - yesterdayClose).toFixed(2);
      const changePercent = ((priceChange / yesterdayClose) * 100).toFixed(2);
      
      // 计算成交量和成交额
      const volume = (parseFloat(elements[8]) / 100 /10000).toFixed(0);
      const amount = (parseFloat(elements[9]) / 100000000).toFixed(2);
      
      // 更新数据
      this.setData({
        stockInfo: {
          name: elements[0],
          currentPrice: elements[3],
          open: elements[1],
          yesterdayClose: elements[2],
          high: elements[4],
          low: elements[5],
          volume: volume + '万',
          amount: amount + '亿',
          date: elements[30],
          time: elements[31],
          priceChange: priceChange > 0 ? '+' + priceChange : priceChange,
          changePercent: changePercent > 0 ? '+' + changePercent : changePercent,
          turnover: '4.43%' // 实际应用中应该计算
        },
        buyOrders: buyOrders,
        sellOrders: sellOrders
      });
    } catch (error) {
      console.error('解析股票数据出错:', error);
    }
  },
  
  // 更新图表URL
  updateChartUrl: function(code) {
    const prefix = code.startsWith('6') ? 'sh' : 'sz';
    const fullCode = prefix + code;
    
    let chartUrl = '';
    switch(this.data.currentTab) {
      case 'minute':
        chartUrl = `http://image.sinajs.cn/newchart/min/n/${fullCode}.gif`;
        break;
      case 'day':
        chartUrl = `http://image.sinajs.cn/newchart/daily/n/${fullCode}.gif`;
        break;
      case 'week':
        chartUrl = `http://image.sinajs.cn/newchart/weekly/n/${fullCode}.gif`;
        break;
      case 'month':
        chartUrl = `http://image.sinajs.cn/newchart/monthly/n/${fullCode}.gif`;
        break;
    }
    
    this.setData({
      chartUrl: chartUrl
    });
  },
  
  // 切换图表类型
  switchTab: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentTab: type
    });
    this.updateChartUrl(this.data.stockCode);
  },

  navigateToNews(e) {
    const news = e.currentTarget.dataset.news;
    wx.navigateTo({
      url: `/pages/news/news?title=${encodeURIComponent(news.title)}&source=${encodeURIComponent(news.source)}&time=${news.time}`
    })
  }
  
})